Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
Is this a function construct feature or Vue 3 or Javascript generally, and how do I pass "this" variables to it?

I am new to Vue 3 and whilst I use Javascript regularly I am not an expert at it. In my Vue 3 project, I found (not on SO) a solution to a particular challenge to deploy Stripe's paymentRequest method. I got the example code to work, but it only works properly when wrapped within this (to me) strange void function construct. However, when wrapped in this construct, I can no longer access variables otherwise available through the 'this' object, so outside the function I can access 'this.myVar' inside I can't.

I found a solution to this but it feels clunky and I am sure there is a better way. The clunky way is to assign any 'this' variables to global javascript variables (within the script tag) just before this construct runs - it works, but doesn't feel the best way by a long stretch. Here is the code in example form...

<script> //section of Vue

var myVar = "";

export default {
  name: 'myVueScreen',
  data() {
    return {
      myVar: "foo",
    },
  }
  methods: {
   myMethod() {

    console.log(this.myVar); //prints 'foo'

    myVar = this.myVar;

    console.log(myVar); //prints 'foo'


    // strange function construct... what is this??
    (function () { 

       console.log(myVar); //prints 'foo'
       console.log(this.myVar); fails with this.myVar undefined

    })(); // I really don't understand the role of the 'extra' ()


   }
  }
}

Can anyone tell me what's actually going on with this (function () {.. construct, why 'this.myVar' is outside scope somehow and therefore failing as undefined, and whether there is a way to pass 'this.myVar' to it without using global JS variables as I currently am... thanks!

BTW, I did find that you can pass variable values into this function as follows, BUT this approach still cannot see 'this.myVar'

So this works...

    (function (bar = "foo") { 

       console.log(bar); //prints 'foo'

...

..and this doesn't, it fails at the first point it tries to read this.myVar:

    (function (bar = this.myVar) { //fails here when reading 'this.myVar'

       console.log(bar); // never reaches this
...
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda